package com.eric.utils;

import java.security.MessageDigest;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;

import com.eric.Config;

public class TextUtils {

	public static String chineseOnly(String s) {
		return s.replaceAll(Config.REGEX_SEPARATOR, "").replaceAll("[0-9a-zA-Z]", "");
	}

	/**
	 * 把中文转成Unicode码
	 * 
	 * @param str
	 * @return
	 */
	public static String chinaToUnicode(String str) {
		String result = "";
		for (int i = 0; i < str.length(); i++) {
			int chr1 = (char) str.charAt(i);
			if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
				result += "\\u" + Integer.toHexString(chr1);
			} else {
				result += str.charAt(i);
			}
		}
		return result;
	}

	/**
	 * 判断是否为中文字符
	 * 
	 * @param c
	 * @return
	 */
	public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * 转换unicode为阅读字符
	 * 
	 * @param unicodeStr
	 * @return
	 */
	public static String decodeUnicode(String unicodeStr) {
		if (unicodeStr == null) {
			return null;
		}
		StringBuffer retBuf = new StringBuffer();
		int maxLoop = unicodeStr.length();
		for (int i = 0; i < maxLoop; i++) {
			if (unicodeStr.charAt(i) == '\\') {
				if ((i < maxLoop - 5) && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr.charAt(i + 1) == 'U')))
					try {
						retBuf.append((char) Integer.parseInt(unicodeStr.substring(i + 2, i + 6), 16));
						i += 5;
					} catch (NumberFormatException localNumberFormatException) {
						retBuf.append(unicodeStr.charAt(i));
					}
				else
					retBuf.append(unicodeStr.charAt(i));
			} else {
				retBuf.append(unicodeStr.charAt(i));
			}
		}
		return retBuf.toString();
	}

	/**
	 * 将字符串用md5方法加密
	 * 
	 * @param s
	 * @return 小写的md5字符串
	 */
	public final static String string2Md5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str).toLowerCase();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static Element removeStyle(Element element) {
		Element e = null;
		if (element.ownText().length() < 10) {
			e = Jsoup.parseBodyFragment(element.html()// 删除字体格式
					.replaceAll("</?strong[^>]*>", "").replaceAll("</?font[^>]*>", "").replaceAll("</?bold[^>]*>", ""));
		} else {
			e = element;
		}

		return e;
	}

	public static Element removeLinks(Element element) {
		Element e = null;
		String name = element.tagName();
		String s = element.toString().replaceAll("</?a[^>]+>", "");
		e = Jsoup.parse(s).getElementsByTag(name).first();
		return e;
	}

	public static String removeBom(String str) {
		return str.replaceAll("\uFEFF", "");
	}

	public static String firstSentence(String text) {
		int begin = 0;
		int end = 0;
		String[] textArray = text.split("");

		for (int i = 0; i < text.length(); i++) {// 向上进行上溯，起始点为sumString的第一个字符，向text的第一个字符上溯
			if (textArray[i].matches("。|\n")) {
				end = i + 1;
				break;
			}
		}
		return text.substring(begin, end);
	}

	/**
	 * 根据提供的summary string，向上和向下截断到句号（。）或者行首处
	 * 
	 * @param sumString
	 * @param simpleText
	 * @return
	 */
	public static String trimSubString(String sumString, String text) {
		int begin = 0, end = 0;
		String simpleText = text;

		String[] textArray = simpleText.split("");

		int sumBegin = simpleText.indexOf(sumString);
		for (int i = sumBegin; i > 0; i--) {// 向上进行上溯，起始点为sumString的第一个字符，向text的第一个字符上溯
			if (textArray[(sumBegin - i)].matches("。|\n")) {
				begin = i + 1;
				break;
			}
		}

		int sumEnd = sumBegin + sumString.length();
		for (int i = 0; i < simpleText.length() - sumEnd; i++) {// 向上进行上溯，起始点为sumString的最后一个字符，向text的最后一个字符下探
			if (textArray[(sumEnd + i)].matches("。|\n")) {
				end = sumEnd + i;
				break;
			}
		}
		System.out.println("Summary Begin : " + begin);
		System.out.println("Summary end : " + end);

		String subString = simpleText.substring(begin, end + 1);

		return subString;
	}

	public static String simplifyText(String text) {
		StringBuilder sb = new StringBuilder();
		String simple;
		for (String s : text.split("")) {
			if (s.matches(com.eric.Config.REGEX_CN_CHAR) || s.matches(com.eric.Config.REGEX_EN_CHAR)
					|| s.matches(com.eric.Config.REGEX_EN_SEPARATOR)
					|| s.matches(com.eric.Config.REGEX_SIMPLE_SEPARATOR) || s.matches("\\d|[<>/=]")) {
				if (!s.matches("&#[0-9];") && !s.matches("&amp;|&gt;|&lt;"))
					sb.append(s);
			}
		}
		simple = sb.toString().replaceAll("&#[0-9];", "").replaceAll("&amp;|&gt;|&lt;|<[^>]*>|&|<|>", "");
		return simple;
	}

}
